# coding: utf-8
# 引入文字识别OCR SDK
from collections import OrderedDict
from aip import AipOcr
import requests
from django.core.cache import cache
from lib.common import CacheKeys
from project.settings import BAIDU_KEYS
from datetime import datetime, timedelta


class BaiDuOCR(object):

    def __init__(self, web_url):
        self.url = web_url

    # 读取本地图片
    def get_file_content(self, filePath):
        with open(filePath, 'rb') as fp:
            return fp.read()

    # 读取网络图片
    def get_file_url(self, weburl):
        response = requests.get(weburl)
        buf = response.content
        return buf
        # f = StringIO.StringIO(buf)
        # return Image.open(f)

    def cache_expire_time(self):
        now_time = datetime.now()
        return 86400 - int(timedelta(hours=now_time.hour, minutes=now_time.minute,
                                              seconds=now_time.second).total_seconds())

    @property
    def aipOcr(self):
        key_detail = BAIDU_KEYS.get(self._key)
        return key_detail

    def orc_function(self, baiduocr):
        return OrderedDict({
            'basic': baiduocr.basicGeneral,
            'general': baiduocr.general,
            'web': baiduocr.webImage
        })

    @property
    def _key(self):
        ids_count = len(BAIDU_KEYS)
        for index in range(ids_count):
            cachekey = CacheKeys.BAIDU_KEY % index
            current_key = cache.get(cachekey)
            if current_key is None:
                cache.set(cachekey, 0, self.cache_expire_time())
                self.key = index
                return index
            if current_key != 1:
                self.key = index
                return index
        assert False, (-1, "当日限额用尽")

    def _function(self, baiduocr):
        for index, values in enumerate(self.orc_function(baiduocr).items()):
            name, func = values
            cachekey = CacheKeys.BAIDU_F_COUNT % (self.key, name)
            current_func = cache.get(cachekey)
            if current_func is None:
                cache.set(cachekey, 1, self.cache_expire_time())
                return func
            if current_func <= 500:
                cache.set(cachekey, current_func+1, self.cache_expire_time())
                return func
            if index == (len(list(self.orc_function(baiduocr).items()))-1) and current_func > 500:
                cache.set(CacheKeys.BAIDU_KEY % self.key, 1, self.cache_expire_time())

        assert False, (-1, "当日限额用尽")

    def baidu_ocr(self):
        api_detail = self.aipOcr
        aipOcr = AipOcr(api_detail['APP_ID'], api_detail['API_KEY'], api_detail['SECRET_KEY'])
        func = self._function(aipOcr)
        result = func(self.get_file_url(self.url))
        return self.handle_result(result)

    def handle_result(self, result):
        assert not result.get('error_code'), (result.get('error_code'), result.get('error_msg'))
        assert result.get('words_result_num') != 0, (-1, "请更换图片，图片需附带正常文字.")
        return "".join([item.get('words') for item in result.get('words_result')])
